package com.owc.service.impl.app;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.owc.common.enums.ExceptionEnum;
import com.owc.common.exception.BadRequestException;
import com.owc.common.tool.BeanUtils;
import com.owc.common.tool.DateUtils;
import com.owc.dao.BannerMapper;
import com.owc.domain.PageBean;
import com.owc.domain.dto.BannerDTO;
import com.owc.domain.entity.Banner;
import com.owc.domain.vo.admin.BannerVo;
import com.owc.domain.vo.admin.QueryVo;
import com.owc.service.ConverterService;
import com.owc.service.app.BannerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author xiaom
 * @Date 2020/2/24 15:00
 * @Version 1.0.0
 * @Description <>
 **/
@Service
@Slf4j
public class BannerServiceImpl implements BannerService, ConverterService<BannerDTO, Banner> {

    @Autowired
    private BannerMapper bannerMapper;

    @Override
    public List<BannerDTO> getBannerList() {
        return convertTo(bannerMapper.selectHomeBanner(8));
    }

    @Override
    public Boolean save(Banner banner) {
        bannerMapper.insert(banner);
        return true;
    }

    @Override
    public PageBean<BannerDTO> pageList(QueryVo queryVo) {
        PageHelper.startPage(queryVo.getPageIndex(), queryVo.getPageSize());
        List<Banner> banners = bannerMapper.selectByFilter(queryVo);
        PageInfo<Banner> pageInfo = new PageInfo<>(banners);
        return PageBean.pageBean(pageInfo.getTotal(), BeanUtils.coventObject(banners,BannerDTO.class));
    }

    @Override
    public Boolean update(BannerVo banner) {
        Banner ubanner = BeanUtils.transformFrom(banner,Banner.class);
        if(ubanner == null){
            throw new BadRequestException(ExceptionEnum.BAD_REQUEST_ERR);
        }
        ubanner.setUpdateTime(DateUtils.formatYMDHMS(new Date()));

        bannerMapper.updateByPrimaryKeySelective(ubanner);
        return true;
    }

    @Override
    public BannerDTO getById(Long id) {
        Banner banner = bannerMapper.selectByPrimaryKey(id);
        return BeanUtils.transformFrom(banner,BannerDTO.class);
    }
}
